<template>
</template>
<script lang="ts">
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js';

// 场景
const scene = new THREE.Scene();

// 相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(10, 10, 10);
camera.lookAt(0, 0, 0);

// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;  // ✅ 开启阴影渲染
document.body.appendChild(renderer.domElement);

// 地板（接收阴影）
const floorGeo = new THREE.PlaneGeometry(20, 20);
const floorMat = new THREE.MeshStandardMaterial({ color: 0x888888 });
const floor = new THREE.Mesh(floorGeo, floorMat);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;  // ✅ 接收阴影
scene.add(floor);

// 立方体（投射阴影）
const cubeGeo = new THREE.BoxGeometry(2, 2, 2);
const cubeMat = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(cubeGeo, cubeMat);
cube.position.set(0, 1, 0);  // 提高1单位，让它浮在地面上
cube.castShadow = true;     // ✅ 投射阴影
scene.add(cube);

// 平行光
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 10, 5);  // 从右上方照射
light.castShadow = true;      // ✅ 开启阴影
light.shadow.radius = 1;
scene.add(light);

// 调整阴影贴图大小（提高质量）
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;

// 阴影相机（控制阴影范围）
light.shadow.camera.left = -10;
light.shadow.camera.right = 10;
light.shadow.camera.top = 10;
light.shadow.camera.bottom = -10;
light.shadow.camera.near = 5;
light.shadow.camera.far = 20;

// 可选：查看光源方向
const helper = new THREE.DirectionalLightHelper(light, 1);
scene.add(helper);

const lightHelp =  new THREE.CameraHelper(light.shadow.camera);
scene.add(lightHelp);

// 控制器
const controls = new OrbitControls(camera, renderer.domElement);

// 渲染循环
function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();


// GUI 控制器
const gui = new GUI();
const lightFolder = gui.addFolder('Light Position');
lightFolder.add(light.position, 'x', -20, 20).onChange(updateHelper);
lightFolder.add(light.position, 'y', 0, 20).onChange(updateHelper);
lightFolder.add(light.position, 'z', -20, 20).onChange(updateHelper);
lightFolder.open();

const shadowCameraHelper = new THREE.CameraHelper(light.shadow.camera);
scene.add(shadowCameraHelper);

function updateHelper() {
  helper.update();
  shadowCameraHelper.update();
}


</script>